import { NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';
import { DeepseekUser } from '@/app/lib/model';
import { connectToDatabase } from '@/app/lib/mongodb'

const secretKey = 'token';

export async function POST(req: Request) {
    try {
        await connectToDatabase()
        const { username, password } = await req.json();

        const user = await DeepseekUser.findOne({ username });
        if (!user) {
            return NextResponse.json(
                { code: 401, msg: '用户名不存在' },
                { status: 401 }
            );
        }

        if (user.password !== password) {
            return NextResponse.json(
                { code: 401, msg: '密码错误' },
                { status: 401 }
            );
        }

        const access_token = jwt.sign({ userId: user._id }, secretKey, { expiresIn: '1h' });
        const refresh_token = jwt.sign({ userId: user._id }, secretKey, { expiresIn: '1h' });

        return NextResponse.json({
            code: 200,
            msg: '登录成功',
            access_token,
            refresh_token
        });

    } catch (err) { 
        return NextResponse.json(
            { code: 500, msg: '服务器错误' },
            { status: 500 }
        );
    }
}